package com.flyco.modules.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.model.DealerAccountDTO;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import com.flyco.modules.system.service.*;
import com.flyco.modules.system.vo.SysUserDTO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.api.vo.Result;
import com.flyco.common.constant.CacheConstant;
import com.flyco.common.constant.CommonConstant;
import com.flyco.common.system.api.ISysBaseAPI;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.system.vo.SysUserCacheInfo;
import com.flyco.common.util.PasswordUtil;
import com.flyco.common.util.UUIDGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.system.entity.*;
import com.flyco.modules.system.mapper.*;
import com.flyco.modules.system.model.SysUserSysDepartModel;
import com.flyco.modules.system.vo.SysUserDepVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @Author: flyco
 * @Date: 2018-12-20
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private SysDepartMapper sysDepartMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysDepartRoleUserMapper departRoleUserMapper;
    @Autowired
    private SysDepartRoleMapper sysDepartRoleMapper;
    @Autowired
    private ISysDepartRoleService sysDepartRoleService;
    @Autowired
    private ISysDepartRoleUserService sysDepartRoleUserService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private ISysUserRoleService userRoleService;

    @Override
    public void addUser(SysUserDTO userDTO) {
        //保存用户信息
        SysUser user = new SysUser();
        user.setPartnerId(1000L);
        user.setRealname(userDTO.getRealname());
        user.setUsername(userDTO.getUsername());
        user.setPhone(userDTO.getUsername());
        user.setTitle(userDTO.getTitle());
        user.setCheckCode(userDTO.getUsername().substring(7));
        user.setQrCode(userDTO.getQrCode());
        user.setType("storeApp");
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(userDTO.getUsername(), userDTO.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setCreateTime(new Date());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        user.setCreateBy(sysUser.getUsername());
        this.save(user);

        //保存用户的角色
        if (StrUtil.isNotBlank(userDTO.getDepartRoleId())) {
            SysDepartRoleUser sysDepartRoleUser = new SysDepartRoleUser();
            sysDepartRoleUser.setUserId(user.getId());
            sysDepartRoleUser.setDroleId(userDTO.getDepartRoleId());
            sysDepartRoleUserService.save(sysDepartRoleUser);
        }

        //保存有权限的门店
        if (StrUtil.isNotBlank(userDTO.getStoreIds())) {
            List<SysUserDepart> collect = Arrays.stream(userDTO.getStoreIds().split(",")).map(storeId -> new SysUserDepart(1000L, null, user.getId(), storeId)).collect(Collectors.toList());
            sysUserDepartService.saveBatch(collect);
        }
    }

    @Override
    public void updateUser(SysUserDTO userDTO) {
        SysUser user = new SysUser();
        user.setId(userDTO.getUserId());
        user.setRealname(userDTO.getRealname());
        user.setQrCode(userDTO.getQrCode());
        user.setTitle(userDTO.getTitle());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        user.setUpdateBy(loginUser.getUsername());
        user.setUpdateTime(new Date());
        this.updateById(user);

        //更新用户的角色
        if (StrUtil.isNotBlank(userDTO.getDepartRoleId())) {
            //删除
            sysDepartRoleUserService.remove(Wrappers.lambdaQuery(SysDepartRoleUser.class).eq(SysDepartRoleUser::getUserId, user.getId()));
            //新增
            SysDepartRoleUser sysDepartRoleUser = new SysDepartRoleUser();
            sysDepartRoleUser.setUserId(user.getId());
            sysDepartRoleUser.setDroleId(userDTO.getDepartRoleId());
            sysDepartRoleUserService.save(sysDepartRoleUser);
        }

        //更新有权限的门店
        if (StrUtil.isNotBlank(userDTO.getStoreIds())) {
            //删除
            sysUserDepartService.remove(Wrappers.lambdaQuery(SysUserDepart.class).eq(SysUserDepart::getUserId, user.getId()));

            //新增
            List<SysUserDepart> collect = Arrays.stream(userDTO.getStoreIds().split(",")).map(storeId -> new SysUserDepart(1000L, null, user.getId(), storeId)).collect(Collectors.toList());
            sysUserDepartService.saveBatch(collect);
        }
    }

    @Override
    public void deleteUserV2(String userId) {
        this.removeById(userId);

        //删除关联信息
        sysDepartRoleUserService.remove(Wrappers.lambdaQuery(SysDepartRoleUser.class).eq(SysDepartRoleUser::getUserId, userId));

        sysUserDepartService.remove(Wrappers.lambdaQuery(SysUserDepart.class).eq(SysUserDepart::getUserId, userId));
    }

    @Override
    public Map<String, Object> detail(String userId) {
        Map<String, Object> result = new HashMap<>(2);

        if (true) {
            SysDepartRoleUser sysDepartRoleUser = sysDepartRoleUserService.getOne(Wrappers.lambdaQuery(SysDepartRoleUser.class).eq(SysDepartRoleUser::getUserId, userId), false);
            if (sysDepartRoleUser != null) {
                SysDepartRole departRole = sysDepartRoleService.getById(sysDepartRoleUser.getDroleId());
                if (departRole != null) {
                    SysDepartRole role = new SysDepartRole();
                    role.setId(departRole.getId());
                    role.setRoleName(departRole.getRoleName());
                    result.put("role", role);
                }
            }
        }

        if (true) {
            List<SysUserDepart> list = sysUserDepartService.list(Wrappers.lambdaQuery(SysUserDepart.class).eq(SysUserDepart::getUserId, userId));
            if (!list.isEmpty()) {
                List<StmStoreInfo> storeInfoList = stmStoreInfoService.list(Wrappers.lambdaQuery(StmStoreInfo.class).select(StmStoreInfo::getId, StmStoreInfo::getStoreId, StmStoreInfo::getName)
                        .in(StmStoreInfo::getId, list.stream().map(SysUserDepart::getDepId).collect(Collectors.toList())));
                result.put("storeInfoList", storeInfoList);
            }
        }

        return result;
    }

    @Override
    public Map<String, SysDepartRole> sysDepartRoleDetails(List<String> userIds) {
        Map<String, SysDepartRole> map = new HashMap<>();

        //查询userId和角色的关联关系
        List<SysDepartRoleUser> list = sysDepartRoleUserService.list(Wrappers.lambdaQuery(SysDepartRoleUser.class)
                .in(SysDepartRoleUser::getUserId, userIds));
        if (!list.isEmpty()) {
            //根据角色id查询角色信息
            Map<String, SysDepartRole> roleMap = sysDepartRoleService.list(Wrappers.lambdaUpdate(SysDepartRole.class)
                    .in(SysDepartRole::getId, list.stream().map(SysDepartRoleUser::getDroleId).collect(Collectors.toList())))
                    .stream().collect(Collectors.toMap(SysDepartRole::getId, a -> a));
            list.forEach(one -> {
                SysDepartRole departRole = roleMap.get(one.getDroleId());
                if (departRole != null) {
                    map.put(one.getUserId(), departRole);
                }
            });
        }

        return map;
    }

    @Override
    public Map<String, List<StmStoreInfo>> stmStoreInfoDetails(List<String> userIds) {
        Map<String, List<StmStoreInfo>> map = new HashMap<>();

        List<SysUserDepart> list = sysUserDepartService.list(Wrappers.lambdaQuery(SysUserDepart.class).in(SysUserDepart::getUserId, userIds));
        if (!list.isEmpty()) {
            Map<String, StmStoreInfo> storeInfoMap = stmStoreInfoService.list(Wrappers.lambdaQuery(StmStoreInfo.class).select(StmStoreInfo::getId, StmStoreInfo::getStoreId, StmStoreInfo::getName)
                    .in(StmStoreInfo::getId, list.stream().map(SysUserDepart::getDepId).distinct().collect(Collectors.toList())))
                    .stream().collect(Collectors.toMap(StmStoreInfo::getId, a -> a));
            Map<String, List<SysUserDepart>> collect = list.stream().collect(Collectors.groupingBy(SysUserDepart::getUserId));
            collect.forEach((userId, l) -> {
                List<StmStoreInfo> storeInfos = new ArrayList<>();
                l.forEach(one -> {
                    StmStoreInfo stmStoreInfo = storeInfoMap.get(one.getDepId());
                    if (stmStoreInfo != null) {
                        storeInfos.add(stmStoreInfo);
                    }
                });
                map.put(userId, storeInfos);
            });
        }

        return map;
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> resetPassword(String username, String oldpassword, String newpassword, String confirmpassword) {
        SysUser user = userMapper.getUserByName(username);
        String passwordEncode = PasswordUtil.encrypt(username, oldpassword, user.getSalt());
        if (!user.getPassword().equals(passwordEncode)) {
            return Result.error("旧密码输入错误!");
        }
        if (oConvertUtils.isEmpty(newpassword)) {
            return Result.error("新密码不允许为空!");
        }
        if (!newpassword.equals(confirmpassword)) {
            return Result.error("两次输入密码不一致!");
        }
        String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
        this.userMapper.update(new SysUser().setPassword(password), new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
        return Result.ok("密码重置成功!");
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> changePassword(SysUser sysUser) {
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        String password = sysUser.getPassword();
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
        sysUser.setPassword(passwordEncode);
        this.userMapper.updateById(sysUser);
        return Result.ok("密码修改成功!");
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(String userId) {
        //1.删除用户
        this.removeById(userId);
        return false;
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchUsers(String userIds) {
        //1.删除用户
        this.removeByIds(Arrays.asList(userIds.split(",")));
        return false;
    }

    @Override
    public SysUser getUserByName(String username) {
        return userMapper.getUserByName(username);
    }


    @Override
    @Transactional
    public void addUserWithRole(SysUser user, String roles) {
        this.save(user);
        if (oConvertUtils.isNotEmpty(roles)) {
            String[] arr = roles.split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole(user.getId(), roleId);
                sysUserRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    @Transactional
    public void editUserWithRole(SysUser user, String roles) {
        this.updateById(user);
        //先删后加
        sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, user.getId()));
        if (oConvertUtils.isNotEmpty(roles)) {
            String[] arr = roles.split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole(user.getId(), roleId);
                sysUserRoleMapper.insert(userRole);
            }
        }
    }


    @Override
    public List<String> getRole(String username) {
        return sysUserRoleMapper.getRoleByUserName(username);
    }

    /**
     * 通过用户名获取用户角色集合
     *
     * @param username 用户名
     * @return 角色集合
     */
    @Override
    public Set<String> getUserRolesSet(String username) {
        // 查询用户拥有的角色集合
        List<String> roles = sysUserRoleMapper.getRoleByUserName(username);
        log.info("-------通过数据库读取用户拥有的角色Rules------username： " + username + ",Roles size: " + (roles == null ? 0 : roles.size()));
        return new HashSet<>(roles);
    }

    /**
     * 通过用户名获取用户权限集合
     *
     * @param username 用户名
     * @return 权限集合
     */
    @Override
    public Set<String> getUserPermissionsSet(String username) {
        Set<String> permissionSet = new HashSet<>();
        List<SysPermission> permissionList = sysPermissionMapper.queryByUser(username);
        for (SysPermission po : permissionList) {
//			// TODO URL规则有问题？
//			if (oConvertUtils.isNotEmpty(po.getUrl())) {
//				permissionSet.add(po.getUrl());
//			}
            if (oConvertUtils.isNotEmpty(po.getPerms())) {
                permissionSet.add(po.getPerms());
            }
        }
        log.info("-------通过数据库读取用户拥有的权限Perms------username： " + username + ",Perms size: " + (permissionSet == null ? 0 : permissionSet.size()));
        return permissionSet;
    }

    @Override
    public SysUserCacheInfo getCacheUser(String username) {
        SysUserCacheInfo info = new SysUserCacheInfo();
        info.setOneDepart(true);
//		SysUser user = userMapper.getUserByName(username);
//		info.setSysUserCode(user.getUsername());
//		info.setSysUserName(user.getRealname());


        LoginUser user = sysBaseAPI.getUserByName(username);
        if (user != null) {
            info.setSysUserCode(user.getUsername());
            info.setSysUserName(user.getRealname());
            info.setSysOrgCode(user.getOrgCode());
        }

        //多部门支持in查询
        List<SysDepart> list = sysDepartMapper.queryUserDeparts(user.getId());
        List<String> sysMultiOrgCode = new ArrayList<String>();
        if (list == null || list.size() == 0) {
            //当前用户无部门
            //sysMultiOrgCode.add("0");
        } else if (list.size() == 1) {
            sysMultiOrgCode.add(list.get(0).getOrgCode());
        } else {
            info.setOneDepart(false);
            for (SysDepart dpt : list) {
                sysMultiOrgCode.add(dpt.getOrgCode());
            }
        }
        info.setSysMultiOrgCode(sysMultiOrgCode);

        return info;
    }

    // 根据部门Id查询
    @Override
    public IPage<SysUser> getUserByDepId(Page<SysUser> page, String departId, String username) {
        return userMapper.getUserByDepId(page, departId, username);
    }

    @Override
    public IPage<SysUser> getUserByDepIds(Page<SysUser> page, List<String> departIds, String username) {
        return userMapper.getUserByDepIds(page, departIds, username);
    }

    @Override
    public Map<String, String> getDepNamesByUserIds(List<String> userIds) {
        List<SysUserDepVo> list = this.baseMapper.getDepNamesByUserIds(userIds);

        Map<String, String> res = new HashMap<String, String>();
        list.forEach(item -> {
                    if (res.get(item.getUserId()) == null) {
                        res.put(item.getUserId(), item.getDepartName());
                    } else {
                        res.put(item.getUserId(), res.get(item.getUserId()) + "," + item.getDepartName());
                    }
                }
        );
        return res;
    }

    @Override
    public IPage<SysUser> getUserByDepartIdAndQueryWrapper(Page<SysUser> page, String departId, QueryWrapper<SysUser> queryWrapper) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = queryWrapper.lambda();

        lambdaQueryWrapper.eq(SysUser::getDelFlag, "0");
        lambdaQueryWrapper.inSql(SysUser::getId, "SELECT user_id FROM sys_user_depart WHERE dep_id = '" + departId + "'");

        return userMapper.selectPage(page, lambdaQueryWrapper);
    }

    @Override
    public IPage<SysUserSysDepartModel> queryUserByOrgCode(String orgCode, SysUser userParams, IPage page) {
        List<SysUserSysDepartModel> list = baseMapper.getUserByOrgCode(page, orgCode, userParams);
        Integer total = baseMapper.getUserByOrgCodeTotal(orgCode, userParams);

        IPage<SysUserSysDepartModel> result = new Page<>(page.getCurrent(), page.getSize(), total);
        result.setRecords(list);

        return result;
    }

    // 根据角色Id查询
    @Override
    public IPage<SysUser> getUserByRoleId(Page<SysUser> page, String roleId, String username) {
        return userMapper.getUserByRoleId(page, roleId, username);
    }


    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, key = "#username")
    public void updateUserDepart(String username, String orgCode) {
        baseMapper.updateUserDepart(username, orgCode);
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, key = "#username")
    public void updateUserPartner(String username, Long partnerId) {
        baseMapper.updateUserPartner(username, partnerId);
    }


    @Override
    public SysUser getUserByPhone(String phone) {
        return userMapper.getUserByPhone(phone);
    }


    @Override
    public SysUser getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    @Transactional
    public void addUserWithDepart(SysUser user, String selectedParts) {
//		this.save(user);  //保存角色的时候已经添加过一次了
        if (oConvertUtils.isNotEmpty(selectedParts)) {
            String[] arr = selectedParts.split(",");
            for (String deaprtId : arr) {
                SysUserDepart userDeaprt = new SysUserDepart(user.getId(), deaprtId);
                sysUserDepartMapper.insert(userDeaprt);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public void editUserWithDepart(SysUser user, String departs) {
        this.updateById(user);  //更新角色的时候已经更新了一次了，可以再跟新一次
        String[] arr = {};
        if (oConvertUtils.isNotEmpty(departs)) {
            arr = departs.split(",");
        }
        //查询已关联部门
        List<SysUserDepart> userDepartList = sysUserDepartMapper.selectList(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, user.getId()));
        if (userDepartList != null && userDepartList.size() > 0) {
            for (SysUserDepart depart : userDepartList) {
                //修改已关联部门删除部门用户角色关系
                if (!Arrays.asList(arr).contains(depart.getDepId())) {
                    List<SysDepartRole> sysDepartRoleList = sysDepartRoleMapper.selectList(
                            new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId, depart.getDepId()));
                    List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                    if (roleIds != null && roleIds.size() > 0) {
                        departRoleUserMapper.delete(new QueryWrapper<SysDepartRoleUser>().lambda().eq(SysDepartRoleUser::getUserId, user.getId())
                                .in(SysDepartRoleUser::getDroleId, roleIds));
                    }
                }
            }
        }
        //先删后加
        sysUserDepartMapper.delete(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, user.getId()));
        if (oConvertUtils.isNotEmpty(departs)) {
            for (String departId : arr) {
                SysUserDepart userDepart = new SysUserDepart(user.getId(), departId);
                sysUserDepartMapper.insert(userDepart);
            }
        }
    }


    /**
     * 校验用户是否有效
     *
     * @param sysUser
     * @return
     */
    @Override
    public Result<?> checkUserIsEffective(SysUser sysUser) {
        Result<?> result = new Result<Object>();
        //情况1：根据用户信息查询，该用户不存在
        if (sysUser == null) {
            result.error500("该用户不存在，请注册");
            sysBaseAPI.addLog("用户登录失败，用户不存在！", CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        //经销商账号不允许登录后台
        if (sysUser.getUserType().equals(3)) {
            result.error500("该用户为经销商，无法登录后台！");
            sysBaseAPI.addLog("该用户为经销商，无法登录后台！", CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        //情况2：根据用户信息查询，该用户已注销
        //update-begin---   Date:20200601  for：if条件永远为falsebug------------
        if (CommonConstant.DEL_FLAG_1.equals(sysUser.getDelFlag())) {
            //update-end---   Date:20200601  for：if条件永远为falsebug------------
            sysBaseAPI.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已注销！", CommonConstant.LOG_TYPE_1, null);
            result.error500("该用户已注销");
            return result;
        }
        //情况3：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(sysUser.getStatus())) {
            sysBaseAPI.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
            result.error500("该用户已冻结");
            return result;
        }
        return result;
    }

    @Override
    public List<SysUser> queryLogicDeleted() {
        return this.queryLogicDeleted(null);
    }

    @Override
    public List<SysUser> queryLogicDeleted(LambdaQueryWrapper<SysUser> wrapper) {
        if (wrapper == null) {
            wrapper = new LambdaQueryWrapper<>();
        }
        wrapper.eq(SysUser::getDelFlag, "1");
        return userMapper.selectLogicDeleted(wrapper);
    }

    @Override
    public boolean revertLogicDeleted(List<String> userIds, SysUser updateEntity) {
        String ids = String.format("'%s'", String.join("','", userIds));
        return userMapper.revertLogicDeleted(ids, updateEntity) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeLogicDeleted(List<String> userIds) {
        String ids = String.format("'%s'", String.join("','", userIds));
        // 1. 删除用户
        int line = userMapper.deleteLogicDeleted(ids);
        // 2. 删除用户部门关系
        line += sysUserDepartMapper.delete(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getUserId, userIds));
        //3. 删除用户角色关系
        line += sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, userIds));
        return line != 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateNullPhoneEmail() {
        userMapper.updateNullByEmptyString("email");
        userMapper.updateNullByEmptyString("phone");
        return true;
    }

    @Override
    public void saveThirdUser(SysUser sysUser) {
        //保存用户
        String userid = UUIDGenerator.generate();
        sysUser.setId(userid);
        baseMapper.insert(sysUser);
        //获取第三方角色
        SysRole sysRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleCode, "third_role"));
        //保存用户角色
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId(sysRole.getId());
        userRole.setUserId(userid);
        sysUserRoleMapper.insert(userRole);
    }

    @Override
    public List<SysUser> queryByDepIds(List<String> departIds, String username) {
        return userMapper.queryByDepIds(departIds, username);
    }

    /**
     * 经销商新增账号或修改密码
     *
     * @param accountDTO
     * @param userType
     * @param realName
     * @return
     */
    @Override
    public Result addUserOrUpdatePwd(DealerAccountDTO accountDTO, Integer userType, String realName) {

        LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(SysUser::getUsername, accountDTO.getUsername());
        List<SysUser> userList = list(userWrapper);

        //没有找到用户，直接创建
        if (CollectionUtils.isEmpty(userList)) {
            //插入用户信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

            SysUser userInfo = new SysUser();
            String salt = oConvertUtils.randomGen(8);
            String password = PasswordUtil.encrypt(accountDTO.getUsername(), accountDTO.getPassword(), salt);
            userInfo = new SysUser();
            userInfo.setCreateBy(sysUser.getUsername());
            userInfo.setPartnerId(1000L);
            userInfo.setPassword(password);
            userInfo.setRealname(realName);
            userInfo.setUserType(userType);
            userInfo.setCreateTime(new Date());
            userInfo.setUsername(accountDTO.getUsername());
            userInfo.setSalt(salt);
            save(userInfo);

            return Result.ok("账号创建成功");
        }
        //如果找到账号，用户类型不匹配，则直接抛出异常
        if (accountDTO.getType().equals(1) && !userList.get(0).getUserType().equals(userType)) {
            return Result.error("新增账号时，发现存在其他类型账号冲突，请修改账号并重试。");
        }

        if (userType.equals(userList.get(0).getUserType())) {
            //更新密码
            SysUser userInfo = userList.get(0);
            if( userInfo.getSalt()==null){
                userInfo.setSalt(oConvertUtils.randomGen(8));
            }
            String password = PasswordUtil.encrypt(accountDTO.getUsername(), accountDTO.getPassword(), userInfo.getSalt());
            userInfo.setPassword(password);
            updateById(userInfo);
            if (accountDTO.getType().equals(0)) {
                return Result.ok("密码更新成功");
            } else {
                return Result.ok("创建成功");
            }
        }
        return Result.ok("成功");
    }

    @Override
    public List<SysUser> getByRoleCode(String roleCode) {

        List<SysUserRole> userRoleList = userRoleService.getByRoleCode(roleCode);
        List<SysUser> userList = new ArrayList<>();

        userRoleList.forEach(o -> {
            SysUser user = getById(o.getUserId());
            if (user != null && user.getStatus().equals(1) && user.getDelFlag().equals(0)) {
                userList.add(user);
            }
        });

        return userList;
    }

    @Override
    public List<SysUser> getByPositionId(Integer positionId) {

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getPositionId, 1)
                .eq(SysUser::getStatus, 1)
                .eq(SysUser::getDelFlag, 0);

        return list(wrapper);
    }

    @Override
    public List<SysUser> getByUserIds(List<Long> userIdList) {

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysUser::getId, userIdList)
                .eq(SysUser::getStatus, 1)
                .eq(SysUser::getDelFlag, 0);

        return list(wrapper);
    }

    @Override
    public List<SysJdUser> getSaleUserList(SysUser sysUser, Integer pageNo, Integer pageSize) {
        Integer startIndex = (pageNo - 1) * pageSize;
        if (pageNo != 1) {
            startIndex = (pageNo - 1) * pageSize + 1;
        }
        Integer endIndex = pageSize;
        return userMapper.getSaleUserList(sysUser, startIndex, endIndex);
    }

    @Override
    public Integer getSaleUserListCount(SysUser sysUser) {
        return userMapper.getSaleUserListCount(sysUser);
    }


    @Override
    public List<SysUser> getByRoleIds(List<String> roleIdList) {

        List<SysUserRole> userRoleList = userRoleService.getByRoleIds(roleIdList);
        List<SysUser> userList = new ArrayList<>();

        userRoleList.forEach(o -> {
            SysUser user = getById(o.getUserId());
            if (user != null && user.getStatus().equals(1) && user.getDelFlag().equals(0)) {
                userList.add(user);
            }
        });

        return userList;
    }

    /**
     * 销售用户同步，只同步系统已经存在的销售人员，
     * 当stm_jd_sales 中的Fnumber变更后，把信息数据更新到user表中。
     * user 表中没有该名称的用户，不用同步。
     */
    @Override
    public void updateUserForSaleUser(){
        userMapper.updateUserForSaleUser();
    }

    @Override
    public void updateUserPwd() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getCreateBy, "import");
        List<SysUser> userList = list(wrapper);
        userList.forEach(x -> {
            String password = PasswordUtil.encrypt(x.getUsername(), "A123456789", x.getSalt());
            x.setPassword(password);
            updateById(x);
        });
    }

}
